import React,{useEffect,useState} from 'react'
import { Skeleton, Card, Avatar,Row,Col,Switch,Drawer,Form ,Select,Input, Button,Popconfirm } from 'antd';

import { EditOutlined, EllipsisOutlined, SettingOutlined,CloseOutlined,PlusOutlined } from '@ant-design/icons';

import {getComponentList,getComponentType,addComponent}from '../../../api/component'
import ComDrawer from '../Drawer'


const { Meta } = Card;
const { Option } = Select;
//表单布局
const layout = {
    labelCol: {
      span: 8,
    },
    wrapperCol: {
      span: 16,
    },
  };
  const tailLayout = {
    wrapperCol: {
      offset: 8,
      span: 16,
    },
  };


const style = { padding: '8px 0' };
export default function Index(props) {
    console.log(props);
   //判断是否需要查询
    let typeNames=props.store.typeNames;
    let typeNameslen=props.store.typeNames.length;

    //设置要存入组件列表的状态
    const[comvalue,setComvalue]=useState([]);
    //设置展示类型
    const[comType,setcomType]=useState([]);
    //设置当前标签页的值
    const[nowcom,setNowcom]=useState({});
    //设置模态框修改还是新增进来的 //
    const[isadd,setIsadd]=useState(false);


    /**
     * 接受单值查询传入的数
     */
    const singvalue=props.store.monodrome;

    //
    let temporary=[];
    
    

     //定义抽屉
     const [visible, setVisible] = useState(false);
     const showDrawer = () => {
       setVisible(true);
     };
   
     const onClose = () => {
       setVisible(false);
     };

    console.log(comvalue);
    function onChange(data){
   
      console.log("气泡框",data);

      //判断当前状态
     const newValue=comvalue.map((item)=>{
        if(item.id===data.id){
          //以及匹配上  修改其状态值
          if(data.state.value==="enabled"){
            
            //说明原先为启动状态  
            item.state.text="以停止";
            item.state.value="disabled"
          }else{
            item.state.text="以启动";
            item.state.value="enabled"
          }
        }
      
        return item;

      })
      console.log("更改状态后的值",newValue);
      //更新状态
      setComvalue(newValue);
    }

    //异步获取展示数据
    let filterlist=[];
    useEffect(()=>{
  
        getComponentList().then((data)=>{
           filterlist=data.data.filter((item)=>{
            for(let i=0;i<typeNames.length;i++){  //TODO  
              // console.log("循环体中逻辑",typeNames[i],item.type);
              if(item.type==typeNames[i]){
                return item;
              }
            }
            
          })

          //TODO:
       
      
        
          //如果单值查询不为空
          if(singvalue!==''){

            console.log("进入");
        
            filterlist=data.data.filter((item)=>{
             
               console.log("单值查询",item,singvalue)
                if(item.name===singvalue){
                  return item;
                }
              
              
            })
              

          }

          console.log("获取到过滤之后的数据",filterlist.length)
          //额先两层for吧
          if(filterlist.length===0 && singvalue===''){
            console.log("无数据");
            setComvalue(data.data);

          }else{    
            setComvalue(filterlist);
          }
       
          
          
        })

    },[typeNames,singvalue]);
     //异步获取展示类型
     useEffect(()=>{
        getComponentType().then((data)=>{
            setcomType(data.data);
        })

    },[comvalue]);


    //卡片的修改
    function edit(data){
         setIsadd(false);
    
        //根据id 查询出对应对象
        const obj=comvalue.filter((item)=>{
            return item.id===data.target.id?item:null;
        })
      
       
        setNowcom(obj[0]?obj[0]:{});
        showDrawer();
       

    }
    //卡片的添加
    function addcom(){
       setIsadd(true);
        showDrawer();

    }
    
    //卡片的删除
    function del(data){

       const filterValue= comvalue.filter((item)=>{
        return  item.id!==data.id?item:null;
        })
       setComvalue(filterValue);

        //获取到列表状态 过滤

    }
   
  
//表单

const [form] = Form.useForm();

  const onGenderChange = (value) => {
    switch (value) {
      case 'male':
        form.setFieldsValue({
          note: 'Hi, man!',
        });
        return;

      case 'female':
        form.setFieldsValue({
          note: 'Hi, lady!',
        });
        return;

      case 'other':
        form.setFieldsValue({
          note: 'Hi there!',
        });
    }
  };

  //抽屉值的添加
  const onFinish = (values) => {
    console.log("表单保存的值",values);
    console.log("获取到当前时间搓",Date.parse(new Date()));

    //构造出可以添加的obj
    const obj =
    {
        id: Date.parse(new Date()),
        name: values.name,
        type: values.type,
        state: {
          text: "以停止",
          value: "disabled"
        }
    }
   
    addComponent(obj).then((data)=>{

        setComvalue([...comvalue,obj])
      
    })
    onClose();

      

  };

   //抽屉值的修改
   const onFinishEdit=(values,e) => {
    //获取到名字使用map进行加工
   const newValues=comvalue.map((item) => {
      if(item.id===values.id){
        item.name=e.name; //更改其值
        return item;
      }
      return item;
    })
    onClose();
    setComvalue(newValues);
  }



  const onFill = () => {
    form.setFieldsValue({
      note: 'Hello world!',
      gender: 'male',
    });
  };

  //气泡框
  function confirm(data){
      console.log("气泡框的",data.target);

  }
  
    return (
        <>
      
        <Row gutter={16}>
      <Col className="gutter-row" span={6}>
      <Card style={{ width: 300,height:165, marginTop: 16 }} loading={false}  onClick={addcom}>
        
        <div className="addPage">
        <PlusOutlined  />新增组件
        </div>
        </Card>

      </Col>
      {comvalue.map((item,index) => {
          return (
              <>
              <Col className="gutter-row" span={6}  key={index}> {/* .id 爆红 待解决 */}
      <Card
        
          style={{ width: 300,height:140, marginTop: 16 }}
          actions={[
            <EditOutlined key="edit" onClick={edit} id={item.id}/>,
            <Popconfirm
        placement="topRight"
        title="确定要删除此组件吗"
        //onConfirm={confirm}
        onConfirm={(e)=>{del(item)}}
        okText="Yes"
        cancelText="No"
        id={item.id}
      >
         <CloseOutlined key="del"/>
      </Popconfirm>
           
            
            // <EllipsisOutlined key="ellipsis" />,
          ]}
        >
          <Skeleton loading={false} avatar active>
            <Meta
              avatar={<Avatar src="https://joeschmoe.io/api/v1/random" />}
              title={item.name}
              description={
                  <>
                   <Row>
                    <Col span={12}>
                        <div>组件类型</div>
                        <div>{item.type}</div>
                    </Col>
                    <Col span={12}>
                        <div>启动状态</div>
                        <div>
                          {/*TODO:  获取到当前状态   决定提示消息 */  }
                        <Popconfirm
                            placement="rightBottom"
                            title={item.state.value==="enabled"?"确认停止":"确认开启"}
                             onConfirm={(e)=>{onChange(item)}}
                            okText="确定"
                            cancelText="取消"
                        >
                           <Switch size="small"  checked={item.state.value==="enabled"} />
                        </Popconfirm>
                            
                            </div>
                    </Col>
                    </Row>
                  </>
              }
            />
          </Skeleton>
        </Card>
              </Col>
              {/* <ComDrawer isShow={isShow} drawer={drawer} /> */}


              </>
          )
      })}

    </Row>



    <>
        <Drawer title={isadd?'新增网络组件':'编辑网络组件'} placement="right" onClose={onClose} visible={visible} width={500}>
         
          <p>{nowcom.id}</p>
          
          <Form form={form} name="control-hooks" onFinish={isadd?onFinish:
            (e)=>onFinishEdit(nowcom,e)
            }>
      <Form.Item
        name="name"
        label="组件名称"
        rules={[
          {
            required: true,
          },
        ]}
      >
        <Input />
      </Form.Item>
      <Form.Item
        name="type"
        label="组件类型"
        defaultValue={nowcom.type}
        // rules={[
        //   {
        //     required: true,
        //   },
        // ]}
      >
        {
          // TODO:
          isadd?temporary.push(comType):temporary.push([nowcom])
          
         
        }
        {
      
           console.log("当前判断的值类型",temporary[0][0].type)
        }
         {
      
          console.log("当前判断的值",temporary[0][0])
      }
        <Select
          placeholder={isadd?"s":nowcom.type}
          onChange={onGenderChange}
          allowClear
          disabled={!isadd}
         // defaultValue={temporary[0][0].type}
        >
            {temporary[0].map((item)=>{
                return (
                  <>
                  {console.log("返回体中",item.type)}
                   <Option value={item.name}>{item.name}</Option>
                 
                  </>
                   

                )

            })}
         
        </Select>
      </Form.Item>
      <Form.Item
        noStyle
        shouldUpdate={(prevValues, currentValues) => prevValues.gender !== currentValues.gender}
      >
        {({ getFieldValue }) =>
          getFieldValue('gender') === 'other' ? (
            <Form.Item
              name="customizeGender"
              label="Customize Gender"
              rules={[
                {
                  required: true,
                },
              ]}
            >
              <Input />
            </Form.Item>
          ) : null
        }
      </Form.Item>
      <Form.Item {...tailLayout}>
        <Button type="primary" htmlType="submit">
          保存
        </Button>
        <Button htmlType="button" onClick={onClose}>
          关闭
        </Button>
      </Form.Item>
    </Form>
        </Drawer>
      </>
      </>
    )
}
